package com.example.huainanlive.server


import android.util.Log
import com.demon.net.NetConstant
import com.example.huainanlive.MyApplication
import okhttp3.FormBody
import okhttp3.FormBody.Builder
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.MultipartBody
import okhttp3.Request
import okhttp3.Response
import java.net.URLDecoder
import java.nio.charset.Charset

/**
 * 类简要描述
 * <p/>
 * <p>
 * 类详细描述
 * </p>
 *
 * @author zhaozeyang
 * @date 2020/8/25
 */
class CommonParamInterceptor : Interceptor {
    override fun intercept(chain: Chain): Response {
        val request = chain.request()
        val newRequest =
            when (request.method) {
                NetConstant.METHOD_GET -> {
                    appendGet(request)
                }
                NetConstant.METHOD_POST -> {
                    appendPost(request)
                }
                else -> {
                    request
                }
            }
        return chain.proceed(newRequest)
    }

    private fun appendGet(request: Request): Request {
        val paramsMap = mutableMapOf<String, String>()
        val paramKeys = request.url.queryParameterNames
        for (key in paramKeys) {
            paramsMap[key] = request.url.queryParameter(key) ?: ""
        }
        return request.newBuilder().url(
            request.url.newBuilder()
//                .addQueryParameter(REQUEST_KEY_TOKEN, MyApplication.apiToken)
                .build()
        ).addHeader(REQUEST_KEY_TOKEN, MyApplication.apiToken!!).build()
    }

    private fun appendPost(request: Request): Request {

        val requestBody = request.body ?: return request
        when (requestBody) {
            is FormBody -> {
                return appendParamToFormBody(requestBody, request)
            }
            is MultipartBody -> {
                return appendParamToMultiPartBody(requestBody, request)
            }
            else -> {
                Log.d("CommonParamInterceptor"," type is %s"+requestBody.javaClass.name)
            }
        }

        return request.newBuilder().addHeader(REQUEST_KEY_TOKEN, MyApplication.apiToken!!).build()
    }

    private fun appendParamToMultiPartBody(
        requestBody: MultipartBody,
        request: Request
    ): Request {
        return request
    }

    private fun appendParamToFormBody(
        requestBody: FormBody,
        request: Request
    ): Request {
        val bodyBuilder = Builder(Charset.defaultCharset())
        var formBody: FormBody = requestBody
        // 先复制原来的参数
        val paramsMap = mutableMapOf<String, String>()
        for (i in 0 until formBody.size) {
            bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i))
            // 生成签名的时候要解码，这里从request里面取出的参数是经过utf-8转码后的字符串，但是生成签名要用原始字符串进行生成
            paramsMap[formBody.encodedName(i)] =
                URLDecoder.decode(formBody.encodedValue(i), Charsets.UTF_8.name())
        }
        // 添加公共参数

        MyApplication.apiToken?.apply {
            formBody = bodyBuilder
                .addEncoded(REQUEST_KEY_TOKEN, this)
                .build()
        }
        return request.newBuilder().post(formBody).build()
    }

    companion object {
        const val REQUEST_KEY_TOKEN = "token"
    }
}